<template>
  <div class="content">
    <div class="head">
      <span class="head-title">包装校验</span>
    </div>
    <div class="main">
      <div class="main-left">
        <div class="left-input">
          <el-checkbox v-model="isInput">是否开启输入</el-checkbox>
          <div class="input-item">
            <span class="item-tip">数量</span>
            <el-input v-model="inputCount" size="small" :disabled="!isInput" @input="inputCountEvent" clearable placeholder="请输入外箱21码数量" class="input"></el-input>
          </div>
        </div>
      </div>
      <div class="main-center">
        <div class="center-head">输入外箱21码</div>
        <div class="center-textarea">
          <el-input type="textarea" :rows="20" placeholder="请扫码输入" v-model="textarea"></el-input>
        </div>
        <div class="center-btn">
          <el-button type="primary" size="small" @click="clear_btn" class="btn-item">清 空</el-button>
          <el-button type="primary" size="small" @click="startValidate_btn" class="btn-item">开始校验</el-button>
        </div>
      </div>
      <div class="main-right">
        <div class="main-icon">
          <i style="cursor: pointer;" class="el-icon-setting" @click="setting_btn" title="设置"></i>
        </div>
      </div>
    </div>
    <!-- 校验结果的dialog -->
    <el-dialog title="校验提示" :visible.sync="resultDialog.isOpen" width="50%" :close-on-press-escape="false" :close-on-click-modal="false" :show-close="false" :modal="false" class="result-dialog">
        <div class="content">
            <div class="content-head">
                <span class="head-tip pass">PASS:{{ resultDialog.passRecord }}</span>
                <span class="head-tip fail">FAIL:{{ resultDialog.failRecord }}</span>
            </div>
            <div class="content-records">
                <span class="records-info">{{resultDialog.validateFailList.length === 0 ? '外箱21码全部校验通过' : '以下外箱21码校验不通过'}}</span>
                <ul class="records-ul">
                    <li class="li-item" v-for="i in resultDialog.validateFailList" :key="i + Math.random()">{{ i }}</li>
                </ul>
            </div>
        </div>
        <span slot="footer" class="dialog-footer">
            <el-button type="primary" @click="resultDialogConfirm_btn" size="small">确 定</el-button>
        </span>
    </el-dialog>
    <!-- 设置dialog -->
    <el-dialog title="提示" :visible.sync="settingFormVisible" width="30%">
      <div class="dialog-checkbox">
        <span class="checkbox-tip" style="margin-right:1vw;font-size: 14px;">选择产线:</span>
        <el-select v-model="lineCode" size="mini" placeholder="请选择">
          <el-option v-for="item in lineCodeList" :key="item.id" :label="item.lineName" :value="item.lineCode"></el-option>
        </el-select>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="settingFormCancel" size="small">取 消</el-button>
        <el-button type="primary" @click="settingFormConfirm" size="small">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { reqUserInfo, reqProductionIPBinds } from "@/api/project.js";
import { reqPackingVerify } from "@/api/packingVerify.js";
import { thorttle, debounce } from "@/utils/tools.js";
export default {
  name: "packingVerify",
  data() {
    return {
      isInput:false,
      inputCount:"",
      textarea:"",
      qualitingForm: {
        username: "zhijianyuan",
        password: "",
      },
      lineCodeList: [],
      lineCode: "",
      settingFormVisible: false,
      resultDialog:{
        isOpen:false,
        passRecord:0,
        failRecord:0,
        validateFailList:[]
      },
      timer:null
    };
  },
  mounted() {
    this.getProductionIPBinds();
    //获取本地存储的相关数据
    const lineInfo = localStorage.getItem("lineInfo") === null ? "" : JSON.parse(localStorage.getItem("lineInfo"));
    //选择性打开dialog选择产线
    if (lineInfo === "") {
      this.settingFormVisible = true;
    } else {
      this.lineCode = lineInfo.lineCode;
    }
    //判断用户身份是否过期
    this.checkIsValidateUser();
  },
  methods: {
    inputCountEvent(event){
      let value = this.inputCount;
      value = value.replace(/[^0-9]/g, '');
      if (value !== '' && !/^(0|[1-9]\d*)$/.test(value)) {
        value = value.slice(0, -1);
      }
      this.inputCount = value;
    },
    //格式化时间函数
    formateDate() {
      const date = new Date();
      let y = date.getFullYear();
      let m = date.getMonth() + 1;
      let d = date.getDate();
      let hour = date.getHours();
      let minutes = date.getMinutes();
      let second = date.getSeconds();
      return (
        y +
        "-" +
        this.addZero(m) +
        "-" +
        this.addZero(d) +
        " " +
        this.addZero(hour) +
        ":" +
        this.addZero(minutes) +
        ":" +
        this.addZero(second)
      );
    },
    //补零函数
    addZero(value) {
      return value > 9 ? value : "0" + value;
    },
    //判断当前用户身份是否过期
    async checkIsValidateUser() {
      let res = await reqUserInfo();
      let isExpired = res.data.data.isExpired;
      if (isExpired) {
        const routeList = this.$router.options.routes;
        let isHasSettingPermission = routeList.findIndex(
          (item) => item.path === "/setting"
        );
        console.log("是否找到了该路由", isHasSettingPermission);
        if (isHasSettingPermission !== -1) {
          //跳转路由,打开重置密码框
          this.$router.push({ path: "/setting" });
        } else {
          //无质检员设置权限
          this.$alert(
            "质检员身份过期，当前用户无质检员设置权限，请联系质检员进行密码重置！（质检员密码重置后刷新页面即可关闭此提示）",
            "提示",
            {
              showConfirmButton: true,
              showClose: false,
              confirmButtonText: "刷新页面",
              beforeClose: (action, instance, done) => {
                //页面刷新
                location.reload();
              },
            }
          );
        }
      }
    },
    //开始校验按钮
    startValidate_btn(){
      if(this.timer !== null){
        clearTimeout(this.timer);
      }
      this.timer = setTimeout(() => {
        this.startIsvalidate();
      },300);
    },
    async startIsvalidate() {
      const inputStr = this.textarea;
      const codeList = inputStr.split('\n').filter(item => item.trim() !== '');
      const lineCode = this.lineCode;
      const count = Number(this.inputCount);
      if(lineCode === ""){
        this.$alert('请先选择产线', '提示', {confirmButtonText: '确定',callback: action => {}});
        return ;
      }
      if(codeList.length === 0){
        this.$alert('请扫码输入外箱21码', '提示', {confirmButtonText: '确定',callback: action => {}});
        return ;
      }
      if(codeList.length !== count){
        this.$alert('输入数量与外箱21码数量不一致', '提示', {confirmButtonText: '确定',callback: action => {}});
        return ;
      }
      reqPackingVerify({lineCode,parentCodes:codeList}).then(response => {
        if(response.data.code === 200){
          const { different,fail,success } = response.data.data;
          this.resultDialog.passRecord = success;
          this.resultDialog.failRecord = fail;
          this.resultDialog.validateFailList = different;
          this.resultDialog.isOpen = true;
        }
        console.log('校验外箱21码api',response);
      }).catch(error => {
        console.log('校验外箱21码api',error);
        this.$message({type:"error",message:"请求失败，请重试"});
      })
    },
    clear_btn(){
      this.textarea = "";
    },
    resultDialogConfirm_btn(){
        this.resultDialog.isOpen = false;
        this.resultDialog.passRecord = 0;
        this.resultDialog.failRecord = 0;
        if(this.resultDialog.validateFailList.length === 0){
          this.textarea = "";
        }
        this.resultDialog.validateFailList = [];
    },
    //设置图标
    setting_btn() {
      this.settingFormVisible = true;
    },
    //获取所有的产线列表接口
    async getProductionIPBinds() {
      let res = await reqProductionIPBinds();
      if (res.data.code === 200) {
        let list = res.data.data.map((item) => {
          return {
            id: item.id,
            lineCode: item.lineCode,
            lineIp: item.lineIp,
            lineName: item.lineName,
          };
        });
        this.lineCodeList = list;
      }
      console.log("产线列表数据", res);
    },
    //settingDialog
    //设置确定按钮
    async settingFormConfirm() {
      if (this.lineCode === "") return;
      this.$message({ type: "success", message: "产线选择成功!" });
      setTimeout(() => {
        this.settingFormVisible = false;
      }, 200);
      //本地存储产线信息
      let lineInfo = this.lineCodeList.filter(
        (item) => item.lineCode === this.lineCode
      )[0];
      localStorage.setItem("lineInfo", JSON.stringify(lineInfo));
    },
    //设置取消按钮
    settingFormCancel() {
      this.settingFormVisible = false;
    },
    //表单校验
    globalCheck() {
      let checkResult = false;
      this.$refs.formData.validate((valid) => {
        checkResult = valid;
      });
      return checkResult;
    },
    partFieldCheck(fieldList) {
      let checkedResultList = [];
      this.$refs.formData.validateField(fieldList, (result) => {
        if (result === "") {
          checkedResultList.push(true);
        } else {
          checkedResultList.push(false);
        }
      });
      return checkedResultList.every((e) => e === true);
    },
  },
};
</script>

<style lang='scss' scoped>
.content {
  width: 100%;
  height: calc(100vh - 50px);
  user-select: none;
  .head {
    width: 100%;
    height: 6%;
    display: flex;
    justify-content: center;
    align-items: center;
    text-align: center;
    background-color: #02b2fd;
    font-size: 1.5vw;
    color: #fff;
  }
  .main {
    width: 100%;
    height: 94%;
    display: flex;
    .main-left{
      width: 30%;
      .left-input{
        width: 90%;
        margin-top: 20%;
        margin-left: 10%;
        display: flex;
        flex-direction: column;
        .input-item{
          margin-top: 10px;
          display: flex;
          align-items: center;
          .input{
            width: 200px;
          }
          .item-tip{
            width:50px;
          }
        }
      }
    }
    .main-center{
      width: 50%;
      height: 100%;
      display: flex;
      flex-direction: column;
      align-items: center;
      .center-head{
        width: 100%;
        height: 10%;
        display: flex;
        justify-content: center;
        align-items: center;
      }
      .center-textarea{
          width: 100%;
      }
      .center-btn{
          width: 100%;
          height: 10%;
          display: flex;
          justify-content: center;
          align-items: center;
          .btn-item{
            margin: 0 20px;
          }
      }
    }
    .main-right{
      width: 20%;
      height: 100%;
      padding: 10px;
      box-sizing: border-box;
      .main-icon{
        display: flex;
        justify-content: flex-end;
      }
    }
  }
}

::v-deep .result-dialog {
  position: absolute;
  left: 30vw;
  top: -8vh;
  .content {
    width: 100%;
    height: 50vh;
    .content-head {
      width: 50%;
      height: 4vh;
      font-size: 1.5vw;
      line-height: 4vh;
      display: flex;
      justify-content: space-between;
      .pass {
        color: #008000;
      }
      .fail {
        color: #f00;
      }
    }
    .content-records {
      width: 100%;
      height: 46vh;
      display: flex;
      flex-direction: column;
      border: 1px dashed #9195a3;
      .records-info {
        font-size: 1.2vw;
      }
      .records-ul {
        width: 100%;
        height: 43vh;
        overflow: auto;
        .li-item {
          font-size: 1.5vw;
        }
      }
    }
  }
}

::v-deep .el-message {
  z-index: 9999;
}
::v-deep .el-dialog__body {
  font-size: 1.5vw;
}
</style>